package com.example.switchingnetwork.util;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkRequest;

import androidx.annotation.NonNull;

import java.util.Timer;
import java.util.TimerTask;

public class HttpUtil {
    ConnectivityManager.NetworkCallback mNetworkCallback;

    /**
     * 强制使用 sim 卡网络
     * @param context 上下文
     * @param callBackNetwork 切换网络后的network的回调
     */
    public void forceSmsNetwork(Context context, ICallBackNetwork callBackNetwork) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkRequest.Builder builder = new NetworkRequest.Builder();
        builder.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET); // 强制使用sim卡网络
        builder.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR);

        // 通过一个延时函数来判断切换蜂窝网络是否成功
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                callBackNetwork.callbackNetwork(null);
            }
        };
        Timer timer = new Timer();
        timer.schedule(timerTask, 3000);

        mNetworkCallback = new ConnectivityManager.NetworkCallback() {
            @Override
            public void onAvailable(@NonNull Network network) {
                super.onAvailable(network);
                timerTask.cancel();
                ConnectivityManager.setProcessDefaultNetwork(network);
                callBackNetwork.callbackNetwork(network);
            }
        };

        NetworkRequest request = builder.build();
        connectivityManager.requestNetwork(request, mNetworkCallback);
    }
}
